package com.v1.video.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.util.Utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
/**
 * 媒体视频列表
 * @author wangfang
 *
 */
public class MediaStoreVideoList extends BaseActivity {

	private LayoutInflater inflater;
	private ListView mListView;
	private TextView mTvTitle;
	private ProgressDialog pd;
	private MyAdapter mAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mediastorevideolist);
	}	

	protected void initView() {
		inflater = getLayoutInflater();
		mListView = (ListView) findViewById(R.id.lv_list);
		mTvTitle = (TextView) findViewById(R.id.tv_title);
	}

	protected void initData() {
		mTvTitle.setText("视频");
		mAdapter = new MyAdapter();
		mListView.setAdapter(mAdapter);
		new VideoListAsync().execute();
	}

	protected void setListener() {
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				if (mAdapter != null && mAdapter.getmDataLst() != null
						&& mAdapter.getmDataLst().size() > position) {
					VideoInfo info = mAdapter.getmDataLst().get(position);
					Intent in = new Intent();
					in.setData(Uri.parse(info.data));
					in.putExtra("thumb", info.thumb);
					setResult(Activity.RESULT_OK, in);
					MediaStoreVideoList.this.finish();
				}
			}
		});

		findViewById(R.id.lay_result).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				MediaStoreVideoList.this.finish();
			}
		});
	}

	// 自定义列表适配器
	private class MyAdapter extends BaseAdapter {

		private List<VideoInfo> mDataLst;

		public MyAdapter() {
			mDataLst = new ArrayList<MediaStoreVideoList.VideoInfo>();
		}

		public List<VideoInfo> getmDataLst() {
			return mDataLst;
		}

		public void setmDataLst(List<VideoInfo> mDataLst) {
			this.mDataLst = mDataLst;
			this.notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mDataLst.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mDataLst.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			PlaceHolder holder;
			if (null == convertView) {
				holder = new PlaceHolder();
				convertView = inflater.inflate(R.layout.activity_mediastorevideolist_item,
						null);
				holder.image = (ImageView) convertView.findViewById(R.id.thumb);
				holder.title = (TextView) convertView.findViewById(R.id.title);
				holder.date = (TextView) convertView.findViewById(R.id.date);
				holder.duration=(TextView)convertView.findViewById(R.id.tv_duration);
				convertView.setTag(holder);
			} else {
				holder = (PlaceHolder) convertView.getTag();
			}

			// FrameLayout.LayoutParams params=new FrameLayout.LayoutParams(
			// FrameLayout.LayoutParams.MATCH_PARENT,
			// FrameLayout.LayoutParams.MATCH_PARENT,
			// android.view.Gravity.CENTER);

			// ImageView img=new ImageView(MediaStoreVideoList.this);
			// img.setImageResource(R.drawable.ic_launcher);
			// holder.thumbfl.removeAllViews();
			// holder.thumbfl.addView(img, params);

			VideoInfo info = mDataLst.get(position);
			if (!TextUtils.isEmpty(info.thumb)) {
				String uri="file:///" + info.thumb;
				ImageLoader.getInstance().displayImage(uri,
						holder.image,Constant.VIDEO_9_16_OPTION);
			} else {
				// Bitmap bitmap=ThumbnailUtils.createVideoThumbnail(info.data,
				// Images.Thumbnails.MICRO_KIND);
				// holder.thumb.setImageBitmap(bitmap);
				// 异步加载缩略图
				 MyAsyncLoadThumb thumbtask = new MyAsyncLoadThumb(
				 MediaStoreVideoList.this, holder.image);
				 thumbtask.execute(info);
			}
			holder.title.setText(info.title);
			holder.date.setText(info.date);

			holder.title.setText(info.title);
			String datestr = new java.text.SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss").format(new java.util.Date(Long
					.parseLong(info.date) * 1000L));
			holder.date.setText(datestr);

//			Calendar cal = Calendar.getInstance();
//			cal.setTimeInMillis(Long.parseLong(info.date) * 1000);
//			holder.date.setText(new java.text.SimpleDateFormat(
//					"yyyy-MM-dd HH:mm:ss").format(cal.getTime())
//					+ "  "
//					+ info.mimetype);
			if(!TextUtils.isEmpty(info.duration+"")){
				holder.duration.setVisibility(View.VISIBLE);
				holder.duration.setText("  "
						+ Utils.millisToString(info.duration));
			} else {
				holder.duration.setVisibility(View.GONE);
			}
			
			return convertView;
		}

		private class PlaceHolder {
			public FrameLayout thumbfl;
			public ImageView image;
			public TextView title;
			public TextView date;
			public TextView duration;
		}

	}

	/**
	 * 获取系统视频信息
	 * @return
	 */
	private List<VideoInfo> getMediaStoreVideos() {
		List<VideoInfo> infos= new ArrayList<VideoInfo>();
		Cursor cursor = null;
		try {
			String[] projection = new String[] { MediaStore.Video.Media._ID,
					MediaStore.Video.Media.DATA,
					MediaStore.Video.Media.DATE_ADDED,
					MediaStore.Video.Media.TITLE,
					MediaStore.Video.Media.MIME_TYPE, 
					MediaStore.Video.Media.DURATION};
			cursor = this.getContentResolver().query(
					MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection,
					null, null, MediaStore.Video.Media.DATE_ADDED + " desc");
			if (null != cursor && cursor.getCount() > 0) {
				while (cursor.moveToNext()) {
					VideoInfo info = new VideoInfo();
					info.id = cursor.getString(cursor
							.getColumnIndex(MediaStore.Video.Media._ID));
					info.data = cursor.getString(cursor
							.getColumnIndex(MediaStore.Video.Media.DATA));
					info.date = cursor.getString(cursor
							.getColumnIndex(MediaStore.Video.Media.DATE_ADDED));
					info.title = cursor.getString(cursor
							.getColumnIndex(MediaStore.Video.Media.TITLE));
					info.mimetype = cursor.getString(cursor
							.getColumnIndex(MediaStore.Video.Media.MIME_TYPE));
					info.duration = cursor.getInt(cursor
							.getColumnIndex(MediaStore.Video.Media.DURATION));
					// 视频相关缩略图
					Cursor thumbcursor = null;
					try {
						String[] projthumb = new String[] { MediaStore.Video.Thumbnails.DATA };
						thumbcursor = this
								.getContentResolver()
								.query(android.provider.MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
										projthumb,
										MediaStore.Video.Thumbnails.VIDEO_ID
												+ "=?",
										new String[] { info.id }, null);
						if (thumbcursor != null && thumbcursor.getCount() > 0) {
							thumbcursor.moveToFirst();
							info.thumb = thumbcursor
									.getString(thumbcursor
											.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
						}
					} finally {
						if (thumbcursor != null) {
							thumbcursor.close();
							thumbcursor = null;
						}
					}
					infos.add(info);
				}
			}
		} finally {
			if (cursor != null) {
				cursor.close();
				cursor = null;
			}
			
		}
		return infos;
	}

	// 定义视频信息对象
	private class VideoInfo {
		public String id;
		public String title;
		public String data;
		public String date;
		public String mimetype;
		public String thumb;
		public int duration;
	}

	// 自定义任务，生成缩略图保存缩略图
	private class VideoListAsync extends AsyncTask<Void, Void, List<VideoInfo>> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			pd = Utils.getProgressDialog(MediaStoreVideoList.this, this);
			pd.show();
		}

		@Override
		protected List<VideoInfo> doInBackground(Void... params) {
			return getMediaStoreVideos();
		}

		@Override
		protected void onPostExecute(List<VideoInfo> result) {
			if (pd != null) {
				if (pd.isShowing()) {
					pd.dismiss();
				}
				pd = null;
			}
			if (result != null && mAdapter != null) {
				mAdapter.setmDataLst(result);
			}
		}
	}

	// 自定义任务，生成缩略图保存缩略图
	private class MyAsyncLoadThumb extends AsyncTask<VideoInfo, Void, Bitmap> {

		private Context mContext;
		private ImageView mImg;

		public MyAsyncLoadThumb(Context cxt, ImageView img) {
			mContext = cxt;
			mImg = img;
		}

		@Override
		protected Bitmap doInBackground(VideoInfo... params) {
			VideoInfo info = params[0];
			String movefile = info.data;
			String moveID = info.id;
			Bitmap bitmap = android.media.ThumbnailUtils.createVideoThumbnail(
					movefile,
					android.provider.MediaStore.Images.Thumbnails.MICRO_KIND);
			if (bitmap == null)
				return null;

			File file = new File(movefile);
			String ThumbnailsPath = file.getParent() + file.separator
					+ file.getName().substring(0, file.getName().indexOf("."))
					+ "thumb.png";
			OutputStream os;
			try {
				os = new java.io.FileOutputStream(ThumbnailsPath);
				bitmap.compress(CompressFormat.PNG, 40, os);
				os.close();
				os = null;

				ContentValues values = new ContentValues();
				values.put(MediaStore.Video.Thumbnails.VIDEO_ID, moveID);
				values.put(MediaStore.Video.Thumbnails.DATA, ThumbnailsPath);
				mContext.getContentResolver().insert(
						MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
						values);
				info.thumb = ThumbnailsPath;

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return bitmap;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			if (result != null) {
				mImg.setImageBitmap(result);
			}
		}
	}
}